<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="requestUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    <!-- 进度条 -->
    <el-progress
      v-if="progressFlag"
      type="circle"
      :percentage="percentage"
      class="progress"
    />
  </el-upload>
</template>

<script>
const Cos = require('cos-js-sdk-v5')
// 实例化对象
const cos = new Cos({
  SecretId: 'AKIDugFZhbGgrnVxA8sMbcOvDG4dx1rSowpT', // 身份识别ID
  SecretKey: 'SfeQyHK8i27xYu1tWv51h8KH1XoqdBUY' // 身份秘钥
})
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imageUrl: '',
      percentage: 0,
      progressFlag: false
    }
  },
  watch: {
    value () {
      this.imageUrl = this.value
    }
  },
  methods: {
    // 完成自定义上传的回调
    requestUpload ({ file }) {
      this.progressFlag = true
      cos.putObject({
        Bucket: 'daming-1312633844', /* 存储桶 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: file, // 上传文件对象
        // 上传进度展示 当前上传了多少了
        onProgress: (progressData) => {
          console.log('进度', JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        console.log('当前返回的信息', data)
        // 上传成功之后
        if (data.statusCode === 200) {
          this.imageUrl = `https:${data.Location}`
          // 自定义事件把url抛出去
          this.$emit('input', this.imageUrl)
        }
        this.progressFlag = false
      })
    },
    // 上传前的校验
    beforeAvatarUpload (file) {
      const ispng = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!ispng) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return ispng && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
}
</style>

